#ifndef TC_MAWEIGHTED_HPP
#define TC_MAWEIGHTED_HPP

/** \file MAWeighted.hpp
 * Definition for the MAWeighted function template.
 *
 * (C) Copyright by Semih Cemiloglu
 * All rights reserved, see COPYRIGHT file for details.
 *
 * $Id: MAWeighted.hpp 110 2006-06-19 03:38:33Z semihc $
 *
 *
 */

#include <QScopedArrayPointer>
#include "TA.hh"
#include "DBC.hpp"

namespace TC {

  //! Weighted moving average function.
  TC_EXPORT template <typename InputIterator,
                      typename OutputIterator,
                      class Adaptor>
  void MAWeighted(InputIterator fromPos,
		  InputIterator fromEnd,
		  OutputIterator toPos,
		  const unsigned period,
		  const Adaptor adaptor)
  {
    TC_PRE_CONDITION(period > 0);

    typedef typename Adaptor::Price_t Price_t;
    QScopedArrayPointer<Price_t> window(new Price_t[period]);
    unsigned widx = 0;

    register unsigned i;
    register TAfp_t wtotal = 0;
    for(i=period; i>0; --i) { 
      wtotal += i;
      window[i-1] = 0;
    }

    register TAfp_t wavg;
    
    for(; fromPos!=fromEnd; ++fromPos) {
      // Store current value
      window[widx] = *fromPos;
      // Calculate weighted average for current window
      wavg = 0;
      for(unsigned pos=widx, i=period; i>0; --i) {
	wavg += window[pos] * i;
	if(pos == 0)
	  pos = period-1;
	else
	  --pos;
      } 
      wavg /= wtotal;
      *toPos++ = wavg;
      // Handle the wrap-around case
      if(++widx==period)
	widx = 0;
    } // end for
    
  }


} // end namespace


#endif /* Include guard */
